package com.tzjw.service;

import com.tzjw.bean.MarketAddress;
import com.tzjw.bean.MarketAddressExample;
import com.tzjw.bean.common.BaseParam;
import com.tzjw.bean.common.CommonData;
import com.tzjw.mapper.MarketAddressMapper;
import com.tzjw.util.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class AddressServiceImpl implements AddressService{
    @Override
    public CommonData queryAddressList(BaseParam baseParam, Integer userId, String name) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketAddressMapper marketAddressMapper = sqlSession.getMapper(MarketAddressMapper.class);

        MarketAddressExample example = new MarketAddressExample();
        // 1.开启分页
        // PageHelper.startPage(1, 20);
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        //example.setOrderByClause("add_time desc");
        example.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        // select * from market_address where user_id = ? and name = ? order by add_time desc limit 0, 20;

        // where user_id = ? and name = ?  这部分可以通过example的方法
        MarketAddressExample.Criteria criteria = example.createCriteria();
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (name != null && !"".equals(name)) {
            // 这里的name不是模糊查询
            //criteria.andNameEqualTo(name);

            // 这里的name是模糊查询
            criteria.andNameLike("%" + name + "%");
        }
        List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(example);

        // 这个sql语句不错分页能查多少条记录出来
        //long count = marketAddressMapper.countByExample(example);

        // 2.获取分页信息
        // 通过分页插件也可以获取一些分页信息
        // 通过PageInfo将上面的查询结果放进去，可以获得分页信息
        PageInfo pageInfo = new PageInfo(marketAddresses);

        sqlSession.close();
        CommonData data = CommonData.data(pageInfo);
        return data;
    }
}
